package com.kaibes.platform.article.listener;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.kaibes.orm.core.listener.DeleteListener;
import com.kaibes.orm.curd.Delete;
import com.kaibes.orm.spring.OrmListener;
import com.kaibes.platform.article.db.entity.ArticleComment;
import com.kaibes.platform.article.db.service.ArticleCommentService;
import com.kaibes.platform.article.db.service.ArticleService;

@OrmListener(service = ArticleCommentService.class)
public class ArticleCommentDeleteListener implements DeleteListener {

    private ThreadLocal<List<ArticleComment>> threadLocal = new ThreadLocal<>();
    
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleCommentService articleCommentService;
    
    @Override
    public void beforeDelete(Delete delete) throws Exception {
        List<ArticleComment> articleComments = articleCommentService.list(delete.getQueries());
        if (!articleComments.isEmpty()) {
            threadLocal.set(articleComments);
        }
    }
    
    @Override
    public void afterClear(int count) throws Exception {
        List<ArticleComment> articleComments = threadLocal.get();
        threadLocal.set(null);
        for (ArticleComment articleComment : articleComments) {
            articleService.minusCommentCount(articleComment.getArticleId());
        }
    }
}
